package com.mmd.common.component;

import com.alibaba.fastjson.JSON;
import com.mmd.bean.CODE;
import com.mmd.bean.WebJsonBean;
import com.mmd.exception.GameException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author cyq
 * @Date 2019/8/30 21:23
 * @Description
 **/
@ControllerAdvice
@ResponseBody
public class WebGlobalExceptionHandler implements HandlerExceptionResolver {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public WebGlobalExceptionHandler() {
    }

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        response.addHeader("Content-Type", "application/json;charset=UTF-8");
        WebJsonBean webJsonBean = null;
        if (StringUtils.isNotBlank(response.getHeader("errorMsg"))) {
            if (StringUtils.isBlank(response.getHeader("errorCode"))) {
                webJsonBean = new WebJsonBean(CODE.API_IS_ERROR);
            } else {
                webJsonBean = new WebJsonBean(Integer.parseInt(response.getHeader("errorCode")), response.getHeader("errorMsg"));
            }

            try {
                response.getWriter().write(JSON.toJSONString(webJsonBean));
            } catch (IOException var11) {
                LOGGER.error("GlobalExceptionHandler write cause IOException", var11);
            }

            return new ModelAndView();
        } else {
            StringBuffer requestURL = request.getRequestURL();
            if (request.getQueryString() != null) {
                requestURL.append("?").append(request.getQueryString());
            }

            String completeURL = requestURL.toString();
            GameException ee;
            if (!(ex instanceof GameException)) {
                LOGGER.error("url:{},referer:{} exception", new Object[]{completeURL, request.getHeader("referer"), ex});
                LOGGER.error("系统异常!{}", ex);
            } else {
                ee = (GameException)ex;
                if (ee != null) {
                    LOGGER.error("url:{},referer:{} exception: TrueMeException code:{}, msg:{}, param:{}, paramObj:{}", new Object[]{completeURL, request.getHeader("referer"), ee.getCode(), ee.getMsg(), ee.getParam(), ee.getParamObj(), ee});
                }
            }

            String taff;
            if (ex instanceof GameException) {
                ee = (GameException)ex;
                webJsonBean = new WebJsonBean(ee.getCode(), ee.getMsg(), ee.getParamObj());
                response.addHeader("errorCode", String.valueOf(ee.getCode()));

                try {
                    taff = URLEncoder.encode(ee.getMsg(), "UTF-8");
                    response.addHeader("errorMsg", taff);
                } catch (UnsupportedEncodingException var13) {
                    LOGGER.error("错误！{}", var13);
                }
            } else if (ex instanceof RuntimeException) {
                String msg = ex.getMessage();
                taff = "com.morning.star.exception.GameException:";
                int index = msg.indexOf(taff);
                if (msg != null && index != -1) {
                    msg = msg.substring(index + taff.length(), msg.indexOf("\n"));
                    webJsonBean = new WebJsonBean(new CODE(1013, msg));
                } else {
                    webJsonBean = new WebJsonBean(CODE.API_IS_ERROR);
                }

                response.addHeader("errorCode", String.valueOf("-9999"));
                response.addHeader("errorMsg", ex.getMessage());
                response.addHeader("errorMsgStack", getExceptionAllinformation(ex));
            } else {
                webJsonBean = new WebJsonBean(CODE.SYSTEMERROR);
                response.addHeader("errorCode", String.valueOf("-9999"));
                response.addHeader("errorMsg", ex.getMessage());
                response.addHeader("errorMsgStack", getExceptionAllinformation(ex));
            }

            try {
                response.getWriter().write(JSON.toJSONString(webJsonBean));
            } catch (IOException var12) {
                LOGGER.error("GlobalExceptionHandler write cause IOException", var12);
            }

            return new ModelAndView();
        }
    }

    public static String getExceptionAllinformation(Exception ex) {
        return ExceptionUtil.getExceptionDetail(ex);
    }

}
